<?php

namespace Modules\Car\Http\Controllers;

use App\Helpers\PayTrait;
use App\Helpers\ResponseData;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Entities\Tci;
//交强险
class TciController extends Controller
{
    use ResponseData,PayTrait;
    public function list(Tci $insurance,Request $request){
        $type = $request->input('type','');
        $car_id = $request->input('car_id','');
        if($type=='all'){
            $data = $insurance->query()
                ->with('car')
                ->when($car_id,function($query)use($car_id){
                    $query->where('car_id',$car_id);
                })
                ->orderBy('id','desc')->get();
        }else{
            $size = $request->input('size',10);
            $data = $insurance->query()
                ->with('car')
                ->when($car_id,function($query)use($car_id){
                    $query->where('car_id',$car_id);
                })
                ->orderBy('id','desc')->paginate($size);
        }
        return $this->success($data);
    }
    public function store(Tci $insurance,Request $request){
        $data = $request->all();
        $car = RecognizeDrivingLicense::query()->find($request->car_id);
        if($car){
            $model = $insurance->query()->create($data);
            if($model){
                //更改车辆使用状态
                $this->changeLimitYear($request->car_id,'tci_end',$model->limit_year);
            }
            return $this->success('保存成功');
        }else{
            $this->failed('车辆不存在',201);
        }

    }
    public function edit(Tci $insurance,Request $request){
        $data = $insurance->find($request->id);
        return $this->success($data);
    }
    public function update(Tci $insurance,Request $request){
        $data = $insurance->find($request->id);
        $data->update($request->all());
        if($request->filled('limit_year')){//商业保险完成
            $this->changeLimitYear($data->car_id,'tci_end',$request->limit_year);
        }
        return $this->success('修改成功');
    }
    public function destory(Tci $insurance,Request $request){
        $data = $insurance->find($request->id);
        $data->delete();
    }
}
